import random

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

# from apps.verification import constants
from apps.verification.constants import IMAGE_CODE_EXPIRE_TIME, SMS_CODE_EXPIRE_TIME, SMS_CODE_FLAG_TIME

from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP


class ImageCodeView(View):
    def get(self, request, uuid):
        # 1.生成图片验证码二进制图片和验证码
        from libs.captcha.captcha import captcha
        # code 图片验证码
        # image 是图片验证码二进制
        code, image = captcha.generate_captcha()
        # 2.记录下来的验证码有一个有效期(redis)
        conn = get_redis_connection('code')
        # conn.setex(key,senconds,value)
        # conn.setex('img:%s'%uuid,120,code)
        conn.setex('img:%s' % uuid, IMAGE_CODE_EXPIRE_TIME, code)
        # 3.把图片返回回去
        # return http.HttpResponse(image)
        # 告知浏览器,以图片的形式解析
        # 如何告知 content_type  语法形式: 大类/小类
        # MIME
        # image/jpeg image/png  image/gif
        # application/json

        return http.HttpResponse(image, content_type='image/jpeg')


from utils.response_code import RETCODE
import logging

logger = logging.getLogger('django')


class SMSCodeView(View):
    """短信验证码"""

    def get(self, reqeust, mobile):
        """
        :param reqeust: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        try:
            # 接收参数
            image_code_client = reqeust.GET.get('image_code')
            uuid = reqeust.GET.get('image_code_id')

            # 校验参数
            if not all([image_code_client, uuid]):
                return http.HttpResponseBadRequest('缺少必传参数')

            # 创建连接到redis的对象
            redis_conn = get_redis_connection('code')
            # 提取图形验证码
            image_code_server = redis_conn.get('img:%s' % uuid)
            if image_code_server is None:
                # 图形验证码过期或者不存在
                return http.HttpResponseBadRequest('图形验证码失效')
            # 对比图形验证码
            if image_code_client.lower() != image_code_server.decode().lower():  # 转小写后比较
                return http.HttpResponseBadRequest('图片验证码输入错误')
            # 删除图形验证码，避免恶意测试图形验证码
            redis_conn.delete('img:%s' % uuid)
            send_flag = redis_conn.get('send_flag:%s' % mobile)
            # redis的数据都是 bytes类型
            # if send_flag is not None and send_flag.decode() == 1:
            if send_flag:
                return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '哥们,你操作太频繁了,嫂子会不高兴的'})
        except Exception as e:
            logger.error(e)
            return http.HttpResponseBadRequest('redis连接错误')

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        # 保存短信验证码
        pl = redis_conn.pipeline()
        # ② 让管道接管我们的redis操作
        pl.setex('sms:%s' % mobile, SMS_CODE_EXPIRE_TIME, sms_code)
        pl.setex('send_flag:%s' % mobile, SMS_CODE_FLAG_TIME, 1)
        # ③ 让管道执行
        pl.execute()
        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        from celery_tasks.sms.tasks import send_sms_code
        # delay 的参数 同 我们的任务参数
        send_sms_code.delay(mobile, sms_code)
        # send_sms_code(mobile,sms_code)

        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})
